# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::BackgroundMigration::BackfillNamespaceIdOfVulnerabilityReads, schema: 20220722145845 do
  let(:namespaces) { table(:namespaces) }
  let(:projects) { table(:projects) }
  let(:users) { table(:users) }
  let(:scanners) { table(:vulnerability_scanners) }
  let(:vulnerabilities) { table(:vulnerabilities) }
  let(:vulnerability_reads) { table(:vulnerability_reads) }

  let(:namespace) { namespaces.create!(name: 'user', path: 'user') }
  let(:project) { projects.create!(namespace_id: namespace.id, project_namespace_id: namespace.id) }
  let(:user) { users.create!(username: 'john_doe', email: 'johndoe@gitlab.com', projects_limit: 10) }
  let(:scanner) { scanners.create!(project_id: project.id, external_id: 'external_id', name: 'Test Scanner') }
  let(:vulnerability) do
    vulnerabilities.create!(
      project_id: project.id,
      author_id: user.id,
      title: 'test',
      severity: 1,
      confidence: 1,
      report_type: 1
    )
  end

  let(:vulnerability_read) do
    vulnerability_reads.create!(
      project_id: project.id,
      vulnerability_id: vulnerability.id,
      scanner_id: scanner.id,
      severity: 1,
      report_type: 1,
      state: 1,
      uuid: SecureRandom.uuid
    )
  end

  subject(:perform_migration) do
    described_class.new(
      start_id: vulnerability_read.vulnerability_id,
      end_id: vulnerability_read.vulnerability_id,
      batch_table: :vulnerability_reads,
      batch_column: :vulnerability_id,
      sub_batch_size: 1,
      pause_ms: 0,
      connection: ActiveRecord::Base.connection
    ).perform
  end

  it 'sets the namespace_id of existing record' do
    expect { perform_migration }.to change { vulnerability_read.reload.namespace_id }.from(nil).to(namespace.id)
  end
end
